# coding=utf-8
"""
    日志记录
"""

import os
import logging
import threading
from flask import g
from logging.handlers import TimedRotatingFileHandler
from utils.do_path import LOG_PATH


# @Time    :  2024-10-30 16:45:12
# @Author  :  jiangtong
# @Email   :  gingerqgyy@outlook.com
# @Project :  flask_ocr
# @File    :  do_logger


class OcrLog(object):
    _logger = None
    _lock = threading.Lock()
    default_trace_id = 'startup'

    @classmethod
    def _acquire_lock(cls):
        cls._lock.acquire()

    @classmethod
    def _release_lock(cls):
        cls._lock.release()

    @classmethod
    def configure_logging(cls, app):
        """ 配置日志记录 """

        log_level = logging.getLevelName(app.config.get('LOG_LEVEL', 'INFO'))
        log_format = '%(asctime)s [%(trace_id)s] %(levelname)s %(process)d --- [%(threadName)s] %(name)s %(lineno)d : %(message)s'
        os.makedirs(LOG_PATH, exist_ok=True)
        log_file = app.config.get('LOG_FILE', os.path.join(LOG_PATH, 'app.log'))

        # 获取并配置 Flask 的 app.logger
        with cls._lock:
            if not cls._logger:
                cls._logger = app.logger
                cls._logger.setLevel(log_level)

                # 禁用默认处理器的传播
                cls._logger.propagate = False

                # 文件 :
                file_handler = TimedRotatingFileHandler(log_file, when='midnight', interval=1, backupCount=7, encoding='utf-8')
                file_handler.setLevel(log_level)
                file_handler.setFormatter(logging.Formatter(log_format))
                cls._logger.addHandler(file_handler)

                # 控制台 :
                console_handler = logging.StreamHandler()
                console_handler.setLevel(log_level)
                console_handler.setFormatter(logging.Formatter(log_format))
                cls._logger.addHandler(console_handler)

        return cls._logger


class TraceIdFilter(logging.Filter):
    def filter(self, record):
        record.trace_id = getattr(g, 'trace_id', OcrLog.default_trace_id)
        return True
